package com.example.demo;


import java.util.concurrent.atomic.AtomicInteger;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;

import reactor.core.publisher.Mono;

public class GrayLevelFilter implements GlobalFilter,Ordered {

	private static final Logger log = LoggerFactory.getLogger(GrayLevelFilter.class);

	private static final AtomicInteger count=new AtomicInteger(1);
	
	@Override
	public int getOrder() {
		return Ordered.HIGHEST_PRECEDENCE;
	}

	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		ServerHttpRequest request=this.request(exchange);
		return chain.filter(exchange.mutate().request(request).build());
	}
	
	private ServerHttpRequest request(ServerWebExchange exchange) { 
		ServerHttpRequest request=exchange.getRequest();
		if(count.getAndUpdate(i->{
			return ++i%Const.GRAY_LEVEL;
		})!=0) {
 			return request;
		}
		log.info("本次请求使用灰度集群响应...");
 		exchange.getAttributes().put(Const.GRAY_LEVEL_MARK, "v1");
 		return request.mutate().header(Const.GRAY_LEVEL_MARK, "v1").build();
	}

}
